<!DOCTYPE html>
<html>
	<head>
		<title>多人聊天室</title>
		<style>
			#chat-box {
				height: 400px;
				border: 1px solid #ccc;
				overflow-y: auto;
				padding: 10px;
			}
			.system-msg {
				color: #666;
				font-style: italic;
			}
			.user-msg {
				margin: 5px 0;
			}
			.username {
				color: #2c3e50;
				font-weight: bold;
			}
		</style>
	</head>
	<body>
		<div id="login">
			<input type="text" id="username" placeholder="输入用户名" />
			<button onclick="joinChat()">加入聊天室</button>
		</div>

		<div id="chat" style="display: none">
			<div id="chat-box"></div>
			<div id="online-users"></div>
			<input type="text" id="message-input" placeholder="输入消息" />
			<button onclick="sendMessage()">发送</button>
		</div>

		<script src="/socket.io/socket.io.js"></script>
		<script>
			const socket = io();
			let currentUser = '';

			// 加入聊天室
			function joinChat() {
				const username = document.getElementById('username').value.trim();
				if (!username) return alert('请输入用户名');

				currentUser = username;
				document.getElementById('login').style.display = 'none';
				document.getElementById('chat').style.display = 'block';
				socket.emit('join', username);
			}

			// 发送消息
			function sendMessage() {
				const input = document.getElementById('message-input');
				const msg = input.value.trim();
				if (msg) {
					socket.emit('message', msg);
					input.value = '';
				}
			}

			// 接收消息
			socket.on('message', data => {
				const chatBox = document.getElementById('chat-box');
				const div = document.createElement('div');

				if (data.type === 'system') {
					div.className = 'system-msg';
					div.textContent = data.content;
				} else {
					div.className = 'user-msg';
					div.innerHTML = `
          <span class="username">${data.username}</span>
          <span>(${data.time}):</span>
          <span>${data.content}</span>
        `;
				}

				chatBox.appendChild(div);
				chatBox.scrollTop = chatBox.scrollHeight;
			});

			// 更新在线用户
			socket.on('users', users => {
				const userList = document.getElementById('online-users');
				userList.innerHTML = `<strong>在线用户(${
					users.length
				}):</strong><br>${users.join('<br>')}`;
			});

			// 回车发送
			document
				.getElementById('message-input')
				.addEventListener('keypress', e => {
					if (e.key === 'Enter') sendMessage();
				});
		</script>
	</body>
</html>
